#!/bin/bash

# fix_network_after_vpn.sh
# 用于修复Ubuntu 24.04安装ViewTurbo VPN后断开连接时网络问题
# 日期: 2025-06-30 (更新)

# 输出带颜色的文本
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

echo -e "${YELLOW}开始诊断网络问题...${NC}"

# 检查脚本是否以root权限运行
if [ "$EUID" -ne 0 ]; then
  echo -e "${RED}请以root权限运行此脚本（sudo bash fix_network_after_vpn.sh）${NC}"
  exit 1
fi

# 1. 检查并重置DNS配置
fix_dns() {
  echo -e "\n${YELLOW}[1/4] 检查DNS配置...${NC}"
  
  # 备份当前resolv.conf
  if [ -f /etc/resolv.conf ]; then
    cp /etc/resolv.conf /etc/resolv.conf.backup.$(date +%Y%m%d%H%M%S)
    echo "已备份当前DNS配置"
  fi
  
  # 检查是否使用systemd-resolved
  if systemctl is-active systemd-resolved >/dev/null 2>&1; then
    echo "重启systemd-resolved服务..."
    systemctl restart systemd-resolved
    
    # 确保resolv.conf指向正确位置
    if [ -L /etc/resolv.conf ]; then
      rm /etc/resolv.conf
      ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf
    else
      echo -e "nameserver 8.8.8.8\nnameserver 114.114.114.114" > /etc/resolv.conf
    fi
  else
    # 直接设置公共DNS
    echo -e "nameserver 8.8.8.8\nnameserver 114.114.114.114" > /etc/resolv.conf
  fi
  
  echo -e "${GREEN}DNS配置已重置为公共DNS服务器${NC}"
}

# 2. 检查并重置网络路由
fix_routes() {
  echo -e "\n${YELLOW}[2/4] 检查网络路由表...${NC}"
  
  # 显示当前路由表
  echo "当前路由表:"
  ip route
  
  # 备份当前路由表
  ip route show > /tmp/route_backup.$(date +%Y%m%d%H%M%S)
  
  # 重置默认路由（获取默认网关）
  default_interface=$(ip -o -4 route show to default | awk '{print $5}' | head -n1)
  
  if [ -z "$default_interface" ]; then
    echo -e "${RED}无法确定默认网络接口，请手动设置路由${NC}"
  else
    default_gateway=$(ip -o -4 route show to default | awk '{print $3}' | head -n1)
    
    if [ -z "$default_gateway" ]; then
      echo -e "${RED}无法确定默认网关地址，尝试从DHCP获取${NC}"
      dhclient -r $default_interface
      dhclient $default_interface
    else
      # 删除可能存在的tun/tap接口路由
      for tun_route in $(ip route show | grep tun); do
        ip route del $tun_route 2>/dev/null
      done
      
      echo -e "${GREEN}已清理VPN路由配置${NC}"
    fi
  fi
}

# 3. 清除系统代理设置
clear_proxy_settings() {
  echo -e "\n${YELLOW}[3/6] 清除系统代理设置...${NC}"
  
  # 清除环境变量中的代理设置
  echo "清除环境变量中的代理设置..."
  unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY
  
  # 检查并清除gsettings系统代理设置（GNOME桌面）
  if command -v gsettings >/dev/null 2>&1; then
    echo "清除GNOME系统代理设置..."
    gsettings set org.gnome.system.proxy mode 'none'
    gsettings set org.gnome.system.proxy.http host ''
    gsettings set org.gnome.system.proxy.http port 0
    gsettings set org.gnome.system.proxy.https host ''
    gsettings set org.gnome.system.proxy.https port 0
    gsettings set org.gnome.system.proxy.socks host ''
    gsettings set org.gnome.system.proxy.socks port 0
    gsettings set org.gnome.system.proxy.ftp host ''
    gsettings set org.gnome.system.proxy.ftp port 0
  fi
  
  # 检查并清除.bashrc和.profile中的代理设置
  echo "检查Shell配置文件中的代理设置..."
  for file in ~/.bashrc ~/.bash_profile ~/.profile ~/.zshrc; do
    if [ -f "$file" ]; then
      # 备份文件
      cp "$file" "${file}.backup.$(date +%Y%m%d%H%M%S)"
      
      # 移除代理设置
      sed -i '/http_proxy=/d; /https_proxy=/d; /HTTP_PROXY=/d; /HTTPS_PROXY=/d; /all_proxy=/d; /ALL_PROXY=/d' "$file"
      echo "已检查并清除 $file 中的代理设置"
    fi
  done
  
  # 检查apt的代理设置
  if [ -f /etc/apt/apt.conf.d/proxy.conf ]; then
    echo "备份并清除APT代理设置..."
    cp /etc/apt/apt.conf.d/proxy.conf /etc/apt/apt.conf.d/proxy.conf.backup.$(date +%Y%m%d%H%M%S)
    echo "" > /etc/apt/apt.conf.d/proxy.conf
  fi
  
  echo -e "${GREEN}系统代理设置已清除${NC}"
}

# 4. 检查ViewTurbo VPN的配置
check_viewturbo_config() {
  echo -e "\n${YELLOW}[4/6] 检查ViewTurbo VPN配置...${NC}"
  
  # 检查ViewTurbo配置目录
  VIEWTURBO_CONFIG_DIR="$HOME/.config/ViewTurbo"
  if [ -d "$VIEWTURBO_CONFIG_DIR" ]; then
    echo "找到ViewTurbo配置目录: $VIEWTURBO_CONFIG_DIR"
    
    # 备份配置文件
    echo "备份ViewTurbo配置文件..."
    BACKUP_DIR="${VIEWTURBO_CONFIG_DIR}_backup_$(date +%Y%m%d%H%M%S)"
    cp -r "$VIEWTURBO_CONFIG_DIR" "$BACKUP_DIR"
    echo "配置已备份到: $BACKUP_DIR"
    
    # 检查代理配置
    if [ -f "$VIEWTURBO_CONFIG_DIR/settings.json" ]; then
      echo "找到设置文件: $VIEWTURBO_CONFIG_DIR/settings.json"
      echo "请在修复后考虑检查该文件中的代理设置"
    fi
  else
    echo "未找到ViewTurbo配置目录"
  fi
  
  # 检查并终止ViewTurbo相关进程
  if pgrep -f "ViewTurbo" >/dev/null || pgrep -f "viewturbocode" >/dev/null; then
    echo "检测到ViewTurbo进程正在运行，尝试停止..."
    pkill -f "ViewTurbo" 2>/dev/null
    pkill -f "viewturbocode" 2>/dev/null
    sleep 2
  fi
  
  echo -e "${GREEN}ViewTurbo配置检查完成${NC}"
}

# 5. 重启NetworkManager服务
restart_network() {
  echo -e "\n${YELLOW}[5/6] 重启网络服务...${NC}"
  
  # 重启网络服务
  systemctl restart NetworkManager
  echo -e "${GREEN}NetworkManager服务已重启${NC}"
  
  # 等待网络重连
  echo "等待网络重连..."
  sleep 5
}

# 6. 测试网络连接
test_connection() {
  echo -e "\n${YELLOW}[6/6] 测试网络连接...${NC}"
  
  # 显示当前网络设备和IP
  echo "当前网络设备:"
  ip addr show | grep -E "^[0-9]+:|inet " | grep -v "127.0.0.1"
  
  # 测试DNS解析
  echo -e "\n测试DNS解析:"
  if host -t A www.baidu.com >/dev/null 2>&1; then
    echo -e "${GREEN}DNS解析成功${NC}"
  else
    echo -e "${RED}DNS解析失败${NC}"
    echo "尝试手动设置DNS..."
    echo -e "nameserver 8.8.8.8\nnameserver 114.114.114.114" > /etc/resolv.conf
  fi
  
  # 测试网络连接
  echo -e "\n测试网络连接:"
  if ping -c 3 -W 2 114.114.114.114 >/dev/null 2>&1; then
    echo -e "${GREEN}ping 114.114.114.114 成功，IP连接正常${NC}"
  else
    echo -e "${RED}ping 114.114.114.114 失败，IP连接异常${NC}"
  fi
  
  if ping -c 3 -W 2 www.baidu.com >/dev/null 2>&1; then
    echo -e "${GREEN}ping www.baidu.com 成功，DNS解析和网络连接正常${NC}"
  else
    echo -e "${RED}ping www.baidu.com 失败，DNS解析或网络连接异常${NC}"
  fi
  
  # 测试HTTP连接
  echo -e "\n测试HTTP连接:"
  if curl -s --connect-timeout 5 http://www.baidu.com -o /dev/null; then
    echo -e "${GREEN}HTTP连接正常${NC}"
  else
    echo -e "${RED}HTTP连接异常${NC}"
  fi
}

# 执行所有修复步骤
fix_dns
fix_routes
clear_proxy_settings
check_viewturbo_config
restart_network
test_connection

# 最终状态汇总
echo -e "\n${YELLOW}============网络修复完成============${NC}"
echo "如果网络仍然不正常，请考虑以下操作："
echo "1. 检查ViewTurbo VPN的配置文件（~/.config/ViewTurbo）"
echo "2. 检查/etc/NetworkManager/NetworkManager.conf是否有特殊配置"
echo "3. 重启计算机以确保所有设置生效"
echo "4. 检查桌面环境的网络设置面板中的代理设置"
echo -e "5. 查看脚本生成的备份文件以进行比较\n"
echo -e "${YELLOW}可以运行以下命令检查网络状态:${NC}"
echo "  ip route                     # 查看路由表"
echo "  cat /etc/resolv.conf         # 查看DNS配置"
echo "  systemd-resolve --status     # 查看DNS解析状态"
echo "  env | grep -i proxy          # 检查代理环境变量"
echo "  gsettings get org.gnome.system.proxy mode  # 检查GNOME代理模式"
echo "  curl -v www.baidu.com        # 详细测试网络连接"
